﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using SqlServerWrapper;
using ResponseObject;
using BartonExtension;
using Model.User;
using Model;

namespace WebSrvs.NET
{
    /// <summary>
    /// Service1 的摘要说明
    /// </summary>
    [System.Web.Script.Services.ScriptService]
    [WebService(Namespace = "http://zker.hk/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。
    // [System.Web.Script.Services.ScriptService]
    public class ZK_UserProcessor : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string checkPhoneExist(int region_header, long uid)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.Text))
                {
                    cmd.CommandText = "select count(*) from user_info_basic where region_header = @region_header and phone = @phone";
                    cmd.Parameters.Add("@region_header", SqlDbType.Int).Value = region_header;
                    cmd.Parameters.Add("@phone", SqlDbType.BigInt).Value = uid;
                    try
                    {
                        var result = cmd.ExecuteScalar();
                        if (result.toInt32().Value == 0)
                        {
                            response.isProcessSuccess = true;
                            response.errCode = ErrorCodes.CODE_ERR_NO_ERR;
                            response.errMsg = ErrorMsgs.MSG_ERR_NO_ERR;
                        }
                        else
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_REG_USER_EXISTS;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_REG_USER_EXISTS;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string checkNicknameExist(string nickname)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.Text))
                {
                    cmd.CommandText = "select count(*) from user_info_basic where nickname = @nickname";
                    try
                    {
                        var result = cmd.ExecuteScalar();
                        if (result.toInt32().Value == 0)
                        {
                            response.errCode = ErrorCodes.CODE_ERR_NO_ERR;
                            response.errMsg = ErrorMsgs.MSG_ERR_NO_ERR;
                        }
                        else
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_REG_NICKNAME_EXISTS;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_REG_NICKNAME_EXISTS;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string doUserRegistration(string user_basic_info_json)
        {
            ZKResponse response = new ZKResponse();
            user_basic_info usr_info = user_basic_info_json.FromJson<user_basic_info>();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_user_basic_info_reg";
                    cmd.Parameters.Add("@region_id", SqlDbType.Int).Value = usr_info.region_header;
                    cmd.Parameters.Add("@phone", SqlDbType.BigInt).Value = usr_info.phone;
                    cmd.Parameters.Add("@nickname", SqlDbType.VarChar).Value = usr_info.nickname;
                    cmd.Parameters.Add("@bind_email", SqlDbType.NVarChar).Value = usr_info.bind_email;
                    cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                        if (returnVal == 0) //success
                        {
                            response.errCode = ErrorCodes.CODE_ERR_NO_ERR;
                            response.errMsg = ErrorMsgs.MSG_ERR_NO_ERR;
                        }
                        else if(returnVal == -1)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_REG_USER_EXISTS;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_REG_USER_EXISTS;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string isLogonDeviceChanged(string device_id,long uid)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.Text))
                {
                    cmd.CommandText = "select last_device_id from user_info_last_logon_device where uid = @uid";
                    cmd.Parameters.Add("@uid", SqlDbType.BigInt).Value = uid;
                    try
                    {
                        var last_device_id = cmd.ExecuteScalar();
                        if (last_device_id.ToString().Equals(device_id))
                        {
                            response.errCode = ErrorCodes.CODE_ERR_NO_ERR;
                            response.errMsg = ErrorMsgs.MSG_ERR_NO_ERR;
                        }
                        else
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_LOGON_DEVICE_ID_NOT_MATCHED;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_LOGON_DEVICE_ID_NOT_MATCHED;
                            response.userinfo = last_device_id.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string bindSNSAccount(long uid,int sns_type, string sns_logonid, string sns_logonpass)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_bind_sns";
                    cmd.Parameters.Add("@uid", SqlDbType.BigInt).Value = uid;
                    cmd.Parameters.Add("@sns_type", SqlDbType.Int).Value = sns_type;
                    cmd.Parameters.Add("@sns_logon_id", SqlDbType.NVarChar).Value = sns_logonid;
                    cmd.Parameters.Add("@sns_logon_pass", SqlDbType.NVarChar).Value = sns_logonpass;
                    cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                        if (returnVal == 0)
                        {
                            
                        }
                        else if(returnVal == -1)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_REG_SNS_ACCT_EXISTS;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_REG_SNS_ACCT_EXISTS;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string doLogonWithPhone(long phone, int region_id)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_get_userinfo";
                    cmd.Parameters.Add("@phone", SqlDbType.BigInt).Value = phone;
                    cmd.Parameters.Add("@regionid", SqlDbType.Int).Value = region_id;
                    try
                    {
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            userinfo info = new userinfo();
                            DataTable dt = new DataTable("userinfo");
                            dt.Load(dr);
                            if (dt.Rows.Count > 0)
                            {
                                info.uid = dt.Rows[0]["id"].toInt32().Value;
                                info.region_id = dt.Rows[0]["region_id"].toInt32().Value;
                                info.phone = dt.Rows[0]["phone"].toInt64().Value;
                                info.nickname = dt.Rows[0]["nickname"].ToString();
                                info.bind_email = dt.Rows[0]["bind_email"].ToString();
                                info.headicon = dt.Rows[0]["headicon_img_path"].ToString();
                                info.roleType = dt.Rows[0]["roleType"].toInt32().Value;
                                info.sns_logon_ids = dt.Rows[0]["sns_logon_ids"].ToString();
                                info.sns_logon_passes = dt.Rows[0]["sns_logon_passes"].ToString();

                                response.userinfo = info;
                            }
                            else
                            {
                                response.isProcessSuccess = false;
                                response.errCode = ErrorCodes.CODE_ERR_ON_LOGON_USER_NOT_EXISTS;
                                response.errMsg = ErrorMsgs.MSG_ERR_ON_LOGON_USER_NOT_EXISTS;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string doRequestSupportedCatalogs()
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.Text))
                {
                    cmd.CommandText = "select id,title,img from catalog_info";
                    try
                    {
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            DataTable dt = new DataTable("catalog");
                            dt.Load(dr);
                            if (dt.Rows.Count > 0)
                            {
                                List<Catalog> catalogs = new List<Catalog>();
                                foreach (DataRow row in dt.Rows)
                                {
                                    Catalog catalog = new Catalog()
                                    {
                                        ID = row["id"].toInt32().Value,
                                        title = row["title"].ToString()
                                    };
                                    catalogs.Add(catalog);
                                }
                                response.userinfo = catalogs;
                            }
                            else
                            {
                                response.isProcessSuccess = false;
                                response.errCode = ErrorCodes.CODE_ERR_ON_REQ_CATALOG_LIST;
                                response.errMsg = ErrorMsgs.MSG_ERR_ON_REQ_CATALOG_LIST;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string doRequestSupportedBrands()
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.Text))
                {
                    cmd.CommandText = "select id,title,location,desc from brand_info";
                    try
                    {
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            DataTable dt = new DataTable("brand");
                            dt.Load(dr);
                            if (dt.Rows.Count > 0)
                            {
                                List<Brand> brands = new List<Brand>();
                                foreach (DataRow row in dt.Rows)
                                {
                                    Brand brand = new Brand()
                                    {
                                        ID = row["id"].toInt32().Value,
                                        title = row["title"].ToString(),
                                        location = row["location"].ToString(),
                                        desc = row["desc"].ToString()
                                    };
                                    brands.Add(brand);
                                }
                                response.userinfo = brands;
                            }
                            else
                            {
                                response.isProcessSuccess = false;
                                response.errCode = ErrorCodes.CODE_ERR_ON_REQ_BRAND_LIST;
                                response.errMsg = ErrorMsgs.MSG_ERR_ON_REQ_BRAND_LIST;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string doCustomizationWithCatalogAndBrand(long uid,string catalogs, string brands)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_user_subscription";
                    cmd.Parameters.Add("@uid", SqlDbType.Int).Value = uid;
                    cmd.Parameters.Add("@brand_subscription", SqlDbType.NVarChar).Value = brands;
                    cmd.Parameters.Add("@catalog_subscription", SqlDbType.NVarChar).Value = catalogs;
                    cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].toInt32().Value;
                        if (returnVal == 0)
                        {

                        }
                        else if (returnVal == -1)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_SUBSCRIPTION_CUSTOMIZATION;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_SUBSCRIPTION_CUSTOMIZATION;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string doRequestCatalogData(long uid,int catalog_id,long req_start_index,int req_length)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_req_catalog_data";
                    cmd.Parameters.Add("@catalog_id", SqlDbType.Int).Value = catalog_id;
                    cmd.Parameters.Add("@req_start_index", SqlDbType.BigInt).Value = req_start_index;
                    cmd.Parameters.Add("@req_length", SqlDbType.Int).Value = req_length;
                    cmd.Parameters.Add("@uid", SqlDbType.BigInt).Value = uid;
                    try
                    {
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            DataTable dt = new DataTable("catalogData");
                            dt.Load(dr);
                            List<Product> products = new List<Product>();
                            foreach (DataRow row in dt.Rows)
                            {
                                Product product = new Product()
                                {
                                    ID = row["id"].toInt64().Value,
                                    title = row["title"].ToString(),
                                    brand_id = row["brand_id"].toInt32().Value,
                                    catalog_id = row["catalog_id"].toInt32().Value,
                                    desc = row["desc"].ToString()
                                };
                                products.Add(product);
                            }
                            response.userinfo = products;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }
    }
}